import { createRouter, createWebHistory } from "vue-router";
import { getToken } from "@/utils/cookie";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/oj/login",
      name: "login",
      component: () => import("@/views/Login.vue"),
    },
    {
      path: "/",
      redirect: "/oj/login",
    },
    {
      path: "/oj/layout",
      name: "layout",
      component: () => import("@/views/Layout.vue"),
      children: [
        {
          path: "Question",
          name: "Question",
          component: () => import("@/views/Question.vue"),
        },
        {
          path: "Competition",
          name: "Competition",
          component: () => import("@/views/Competition.vue"),
        },
        {
          path: "user",
          name: "user",
          component: () => import("@/views/UserManage.vue"),
        },
        {
          path: "test",
          name: "test",
          component: () => import("@/views/Test.vue"),
        },
        {
          path: "updateExam",
          name: "updateExam",
          component: () => import("@/views/UpdateExam.vue"),
        },
      ],
    },
  ],
});

/**
 * 登录拦截
 * 1. 未登录，跳转到登录页
 * 2. 已登录，跳转到目标页
 */
router.beforeEach((to, from, next) => {
  if (getToken()) {
    if (to.path === "/oj/login") {
      next("/oj/layout");
    } else {
      next();
    }
  } else {
    if (to.path !== "/oj/login") {
      next({
        path: "/oj/login",
      });
    } else {
      next();
    }
  }
});

export default router;
